package com.gml.jdk.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynaicTest implements InvocationHandler {

    Object originalObj;

    Object bind(Class clazz) throws IllegalAccessException, InstantiationException {
        this.originalObj = clazz.newInstance();
        return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(), originalObj.getClass().getInterfaces(), this::invoke);
    }

    /**
     *
     * @param proxy 是代理的对象
     * @param method    是IHello的sayHello接口
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("开始调用");
        //此处不要使用"proxy"来作为方法执行的参数，容易出现死循环现象，此处应传入被代理类的实例
        return method.invoke(originalObj, args);
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        IHello hello = (IHello) new DynaicTest().bind(Hello.class);
        hello.sysHello();
    }
}
